package com.miracle.main.module.mvp.presenter;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
import com.miracle.basemvp.base.BasePresenter;
import com.miracle.basemvp.base.BaseResponse;
import com.miracle.basemvp.base.IPresenter;
import com.miracle.basemvp.network.download.ProgressDownloadListener;
import com.miracle.basemvp.network.download.RetrofitClient;
import com.miracle.basemvp.util.CommonDialogUtils;
import com.miracle.basemvp.util.Utils;
import com.miracle.common.CommonConfig;
import com.miracle.common.mvp.entity.request.CheckVersionRequest;
import com.miracle.common.util.PreferencesUtils;
import com.miracle.common.util.VersionUtil;
import com.miracle.main.module.mvp.contract.SettingContract;
import com.miracle.common.mvp.entity.response.DandelionResponse;
import com.miracle.common.mvp.entity.response.VersionInfo;
import com.miracle.main.module.mvp.entity.bean.FileItem;
import com.miracle.main.module.mvp.entity.response.UploadResponse;
import com.miracle.main.util.FileUploadObserver;
import com.miracle.main.util.MultipartBuilder;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.trello.rxlifecycle2.LifecycleProvider;
import com.trello.rxlifecycle2.android.ActivityEvent;
import com.trello.rxlifecycle2.android.FragmentEvent;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import okhttp3.MultipartBody;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

import static com.miracle.common.CommonConfig.PGY_API_KEY;
import static com.miracle.common.CommonConfig.PGY_APP_KEY;

/**
 * com.miracle.main.module.mvp.presenter
 * (c)2018 AIR Times Inc. All rights reserved.
 *
 *
 * @author WangJQ
 * @version 1.0
 * @date 2018/7/7 13:25
 * @see com.miracle.main.module.mvp.presenter
 */
public class SettingPresenter extends BasePresenter<SettingContract.View, SettingContract.Model>
        implements IPresenter {


    @Inject
    public SettingPresenter(SettingContract.View view, SettingContract.Model model) {
        super(view, model);
    }

    public void uploadFiles(LifecycleProvider<FragmentEvent> lifecycleProvider, String path) {
        final CommonDialogUtils commonDialogUtils = new CommonDialogUtils(((Fragment) mView)
                .getActivity());
        commonDialogUtils.showProgress();
        FileUploadObserver fileUploadObserver = new FileUploadObserver<ResponseBody>() {
            @Override
            public void onUploadSuccess(ResponseBody o) {
                commonDialogUtils.dismissProgress();
                UploadResponse response = format(((Fragment) mView)
                        .getActivity(), o);
                if (response != null && response.getContent() != null && !TextUtils.isEmpty(response.getContent()
                        .getPath())) {
                    mView.onUploadSucc(response.getContent()
                            .getPath());
                } else {
                    mView.onUpLoadFail("");
                }
            }

            @Override
            public void onUploadFail(Throwable e) {
                commonDialogUtils.dismissProgress();
                mView.onUpLoadFail("");
            }

            @Override
            public void onProgress(int progress) {
                Log.d("WJQ", "onProgress");
            }
        };
        //
        String session = PreferencesUtils.getPreferences(((Fragment) mView).getActivity(),
                PreferencesUtils
                        .State.USER_SESSIONID);
        //
        String url = CommonConfig.BASE_URL+"updateTx";
        File file = new File(path);
        ArrayList<File> files = new ArrayList<>();
        files.add(file);
        MultipartBody body = MultipartBuilder.filesToMultipartBody(files,
                fileUploadObserver, session);

        mModel.uploadFiles(url, body, session)
                .compose(lifecycleProvider.<ResponseBody>bindUntilEvent
                        (FragmentEvent.DESTROY))
                .subscribe(fileUploadObserver);
    }

    public UploadResponse format(Context context, ResponseBody responseBody) {
        UploadResponse response = null;
        try {
            if (responseBody != null) {
                long contentLength = responseBody.contentLength();
                BufferedSource source = responseBody.source();
                source.request(Integer.MAX_VALUE);
                Buffer buffer = source.buffer();
                if (contentLength != 0) {
                    Gson gson = Utils.obtainAppComponentFromContext(context).gson();
                    response = gson.fromJson(buffer.clone().readString(Charset.forName("UTF-8")),
                            UploadResponse.class);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }

    /**
     * 检查版本
     * @param lifecycleProvider
     */
    public void checkVersion(LifecycleProvider<FragmentEvent> lifecycleProvider) {
        final Context context = (mView instanceof Activity) ? (Activity) mView :
                ((Fragment) mView).getActivity();
        CheckVersionRequest request = new CheckVersionRequest();
        //当前版本号
        final int currVersion = VersionUtil.getLocalVersion(context);
        //设置蒲公英需要的api 和 app key
        request.set_api_key(PGY_API_KEY);
        request.setAppKey(PGY_APP_KEY);
        mModel.checkVersion(request)
                .compose(lifecycleProvider.<DandelionResponse<VersionInfo>>bindUntilEvent
                        (FragmentEvent.DESTROY))
                .subscribe(new Observer<DandelionResponse<VersionInfo>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(DandelionResponse<VersionInfo>
                                               versionInfoDandelionResponse) {
                        if ("0".equals(versionInfoDandelionResponse.getCode())) {
                            VersionInfo info = versionInfoDandelionResponse.getData();
                            if (info != null) {
                                try {
                                    int infoNo = Integer.parseInt(info.getBuildVersionNo());
                                    PreferencesUtils.setIntPreferences(context,
                                            PreferencesUtils.Version.VERSION_NEWEST, infoNo);
                                    PreferencesUtils.setPreferences(context, "url", info
                                            .getDownloadURL());
                                    if (currVersion < infoNo) {
                                        mView.FindANewVersion(info.getBuildUpdateDescription());
                                    } else {
                                        mView.NoNewVersion();
                                    }
                                } catch (NumberFormatException e) {
                                    mView.NoNewVersion();
                                }
                            }

                        } else {

                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public void downloadApk(LifecycleProvider<FragmentEvent> lifecycleProvider, String url,
                            final ProgressDownloadListener listener) {
        url = PreferencesUtils.getPreferences(((Fragment) mView).getActivity(), "url");
        // 文件夹地址
        String filePath = Environment.getExternalStorageDirectory() + "/WeCloud";
//        String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() +
// "/WeCloud";
        // 根据url获取文件
        File updateFile = new File(filePath);
        // 判断文件夹是否存在,如果不存在则创建文件夹
        if (!updateFile.exists()) {
            updateFile.mkdir();
        }
        String apkFullName = filePath + "/wecloud.apk";

        RetrofitClient.getInstance(listener)
                .downloadFiles(url, new Consumer<InputStream>() {
                    @Override
                    public void accept(InputStream fileInputStream) throws Exception {
                        listener.onFinishDownload();
                        Log.d("WJQ", "onFinish");
                    }
                }, apkFullName);
    }
}
